<template>
  <div class="app-container">
    <!-- 搜索区域保持不变 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品ID" prop="productId">
        <el-input
            v-model="queryParams.productId"
            placeholder="请输入产品ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序ID" prop="operationId">
        <el-input
            v-model="queryParams.operationId"
            placeholder="请输入工序ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 次品卡片展示区 -->
    <div class="defective-cards-container">
      <div
          v-for="item in goodsListWithProductName"
          :key="item.id"
          class="defective-card"
          :class="{ 'active': selectedItem?.id === item.id }"
          @click="handleSelectItem(item)"
      >
        <div class="card-header">
          <span class="product-id">{{ item.id }}</span>
          <el-tag :type="getStatusTagType(item.status)" size="small">
            {{ item.status || '待处理' }}
          </el-tag>
        </div>
        <div class="product-name">{{ item.productName || '未命名产品' }}</div>
<!--        <div class="problem-brief">{{ shortenProblemDesc(item.problemDes) }}</div>-->
      </div>
    </div>

    <!-- 次品详情展示区 -->
    <div class="detail-panel" v-if="selectedItem">
      <div class="detail-header">
        <h3>次品详情</h3>
        <div class="action-buttons">
          <el-button type="success" @click="handleQualified">判定合格</el-button>
          <el-button type="danger" @click="showUnqualifiedDialog">判定不合格</el-button>
        </div>
      </div>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品ID">{{ selectedItem.productId }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ selectedItem.productName }}</el-descriptions-item>
        <el-descriptions-item label="工序ID">{{ selectedItem.operationId }}</el-descriptions-item>
        <el-descriptions-item label="提供者">{{ selectedItem.supplyer }}</el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">
          {{ selectedItem.problemDes }}
        </el-descriptions-item>
<!--        <el-descriptions-item label="创建时间">{{ selectedItem.createTime }}</el-descriptions-item>-->
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusTagType(selectedItem.status)">
            {{ selectedItem.status || '待处理' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 不合格处置对话框（修正版） -->
    <el-dialog v-model="unqualifiedDialogVisible" title="不合格处置" width="700px">
      <el-form :model="dispositionForm" label-width="120px">
        <!-- 处置方式 -->
        <el-form-item label="处置建议" required>
          <el-radio-group v-model="dispositionForm.dispositionProposal">
            <el-radio label="返工">返工</el-radio>
            <el-radio label="报废">报废</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 产品信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联产品ID">
              <el-input
                  v-model="dispositionForm.productId"
                  :placeholder="selectedItem?.productId"
                  disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" required>
              <el-input
                  v-model="dispositionForm.unitOfMeasure"
                  placeholder="如：件、个"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 缺陷信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缺陷类型" required>
              <el-select
                  v-model="dispositionForm.defectTypeId"
                  style="width:100%"
              >
                <el-option
                    v-for="(item, index) in typesName"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人">
              <el-input
                  v-model="dispositionForm.createdBy"

              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 问题描述 -->
        <el-form-item label="问题描述">
          <el-input
              v-model="dispositionForm.problemDescription"
              type="textarea"
              :rows="3"
              :placeholder="selectedItem?.problemDes || '暂无描述'"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="unqualifiedDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitDisposition"
            :loading="submitting"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listGoods, updateGoods, fail, delGoods,addReports, pass} from "@/api/quality-service/goods"
import { ElMessage, ElMessageBox } from 'element-plus'
import {listProducts} from "@/api/base-data-service/products.js";
import {listTypes} from "@/api/quality-service/types.js";
import useUserStore from "@/store/modules/user.js";

const { proxy } = getCurrentInstance()

const goodsList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const selectedItem = ref(null)
const unqualifiedDialogVisible = ref(false)
const productsList = ref([])
const productsName = ref([])
const typesList = ref([])
const typesName = ref([])
const userStore = useUserStore()
const userName = userStore.name
const unitOfMeasures = ref([])


// 查询参数和原有方法保持不变
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    operationId: null,
    problemDes: null,
    supplyer: null
  }
})

const dispositionForm = ref({
  productId: '',
  unitOfMeasure: '',
  defectTypeId: null,
  problemDescription: '',
  dispositionProposal: '',
  createdBy: userName // 替换为实际用户获取方式
})

// 显示对话框时初始化数据
function showUnqualifiedDialog() {
  if (!selectedItem.value) return

  dispositionForm.value = {
    productId: selectedItem.value.productId,
    unitOfMeasure: selectedItem.value.unitOfMeasure, // 默认值
    defectTypeId: null,
    problemDescription: selectedItem.value.problemDes,
    dispositionProposal: '返工', // 默认选择返工
    createdBy: userName, // 实际替换为 getUser().name
    // 其他字段...
  }

  unqualifiedDialogVisible.value = true
}

const { queryParams } = toRefs(data)

/** 查询列表 */
function getList() {
  loading.value = true
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows
    loading.value = false
  })
  listProducts(queryParams.value).then(response => {
    productsList.value = response.rows
    productsName.value = productsList.value.map(item => ({
      value: item.productId,
      label: item.productName
    }))
    unitOfMeasures.value = productsList.value.map(item => ({
      value: item.productId,
      label: item.unitOfMeasure
    }))
    total.value = response.total
    loading.value = false
  })
  listTypes(queryParams.value).then(response => {
    typesList.value = response.rows
    typesName.value = typesList.value.map(item => ({
      value: item.defectTypeId,
      label: item.defectName
    }))
    total.value = response.total
    loading.value = false
  })
}
const productMap = computed(() => {
  return new Map(productsName.value.map(m => [m.value, m.label])) // 显式返回
})

const unitMap = computed(() => {
  return new Map(unitOfMeasures.value.map(m => [m.value, m.label])) // 显式返回
})

const goodsListWithProductName = computed(() => {
  return goodsList.value.map(c => ({ // 显式返回 + 正确对象语法
    ...c,
    productName: productMap.value.get(c.productId) || '未知物料',
    unitOfMeasure: unitMap.value.get(c.productId  || '默认单位')
  }))
})


/** 选择次品 */
function handleSelectItem(item) {
  selectedItem.value = item
}

/** 缩短问题描述 */
function shortenProblemDesc(desc) {
  if (!desc) return ''
  return desc.length > 20 ? desc.substring(0, 20) + '...' : desc
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  switch (status) {
    case '合格': return 'success'
    case '返工': return 'warning'
    case '报废': return 'danger'
    default: return 'info'
  }
}

/** 判定合格 */
function handleQualified() {
  if (!selectedItem.value) return

  proxy.$modal.confirm('确认将该产品标记为合格吗？').then(() => {
    // 构建符合后端要求的mesBadGoods对象
    const mesBadGoods = {
      id: selectedItem.value.id,
      productId: selectedItem.value.productId,
      operationId: selectedItem.value.operationId,
      // 根据您的数据库表结构，可以添加其他必要字段
      problemDes: selectedItem.value.problemDes,
      supplyer: selectedItem.value.supplyer
    }

    // 调用pass接口，传递整个mesBadGoods对象
    pass(mesBadGoods).then(() => {
      ElMessage.success('操作成功')
      getList()
      selectedItem.value = null
    }).catch(error => {
      ElMessage.error(error.message || '操作失败')
    })
  }).catch(() => {
    // 用户取消操作
  })
}



/** 文件上传处理 */
function handleFileChange(file) {
  dispositionForm.value.attachments.push(file)
}

const submitDisposition = async () => {
  if (!validateForm()) return

  try {
    // 构建报告数据（包含所有表格字段）
    const reportData = {
      productId: selectedItem.value.productId,
      unitOfMeasure: dispositionForm.value.unitOfMeasure,
      defectTypeId: dispositionForm.value.defectTypeId,
      problemDescription: dispositionForm.value.problemDescription,
      dispositionProposal: dispositionForm.value.dispositionProposal,
      createdBy: dispositionForm.value.createdBy, // 替换为实际用户获取
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      // 关联字段
      operationId: selectedItem.value.operationId,
      originalProblem: selectedItem.value.problemDes
    }

    // 1. 先提交不合格报告
    await addReports(reportData)

    // 2. 执行处置操作
    if (dispositionForm.value.dispositionProposal === '返工') {
      await fail({ id: selectedItem.value.id ,
                                productId: selectedItem.value.productId ,
                                operationId: selectedItem.value.operationId ,
                                problemDes: selectedItem.value.problemDes ,
                                supplyer: selectedItem.value.supplyer ,})
    } else {
      await ElMessageBox.confirm('确认报废？此操作不可撤销！', '警告', {
        type: 'warning'
      })
      await delGoods(selectedItem.value.id)
    }

    ElMessage.success('处置成功')
    unqualifiedDialogVisible.value = false
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '处置失败')
    }
  }
}

// 表单验证
const validateForm = () => {
  const requiredFields = [
    'unitOfMeasure',
    'defectTypeId',
    'dispositionProposal'
  ]

  for (const field of requiredFields) {
    if (!dispositionForm.value[field]) {
      ElMessage.error(`请填写${getFieldLabel(field)}`)
      return false
    }
  }
  return true
}

// 字段标签映射
const getFieldLabel = (field) => {
  const labels = {
    unitOfMeasure: '计量单位',
    defectTypeId: '主要缺陷类型',
    dispositionProposal: '处置建议'
  }
  return labels[field] || field
}
// 保留原有的搜索、重置等方法
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.defective-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
  max-height: 40vh;
  overflow-y: auto;
  padding: 8px;
}

.defective-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.defective-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.defective-card.active {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.product-id {
  font-weight: bold;
  color: #303133;
}

.product-name {
  font-size: 16px;
  margin-bottom: 8px;
  color: #606266;
}

.problem-brief {
  font-size: 14px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-panel {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
  background-color: #fff;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-header h3 {
  margin: 0;
  color: #303133;
}

.el-dialog__body {
  padding: 20px;
}


.el-form-item.is-required .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}


.el-textarea__inner {
  min-height: 80px;
}
</style>